<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="form.uname"/>
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="form.age"/>
    </div>
    <div>
      <span>性别:</span>
      <select v-model="form.gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="kdealclick">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item,index) in lis" :key="item.id">
          <td>{{index}}</td>
          <td>{{item.uname}}</td>
          <td>{{item.age}}</td>
          <td>{{item.gender}}</td>
          <td>
            <button @click="remove(item.id)">删除</button>
            <button @click="edit(item.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data(){
    return{
      lis:JSON.parse(localStorage.getItem('lis'))||[],
      form:{
        uname:'',
        age:'',
        gender:''
      }
    }
  },
  watch:{
    lis:{
      deep:true,
      handler(){
        localStorage.setItem('lis',JSON.stringify(this.lis))
      }
    }
  },
  methods:{
    kdealclick(){
      if(this.form.id){
        this.lis.splice(this.lis.findIndex(item=>item.id===this.form.id),1,{...this.form})
      }else{
         if(this.form.gender===''||this.form.uname===''||this.form.age==='')return alert("请输入有效信息")
        this.form.id=this.lis.length?this.lis.slice(-1)[0].id+1:1
        this.lis.push({...this.form})
      }
      this.form.uname=this.form.age=this.form.gender=this.form.id=''
    },
    remove(id){
      this.lis.splice(this.lis.findIndex(item=>item.id===id),1)
    },
    edit(id){
      const item=this.lis.find(item=>item.id===id)
      this.form.gender=item.gender
      this.form.uname=item.uname
      this.form.age=item.age
      this.form.id=item.id
    }
  }
}
</script>